<?php

namespace app\services;

use app\traits\Page;
use plugin\admin\app\model\CallUser;
use plugin\admin\app\model\Like;
use plugin\admin\app\model\UserFollowing;
use plugin\admin\app\model\UserProfile;
use plugin\admin\app\model\Video;
use plugin\admin\app\model\VideoComment;

class CallUserService
{
    public static function list($page, $length = 10)
    {
        $offset = ($page - 1) * $length;

        $query = CallUser::where('call_user_id', get_user_id());

        $totalCount = (clone $query)->count();
        $list = $query->offset($offset)->limit($length)->orderByDesc('id')->get()->toArray();

        $callUserIds = array_column($list, 'user_id');
        $callUsers =  UserProfile::select(['user_id', 'nickname', 'avatar', 'no'])->whereIn('user_id', $callUserIds)->get()->toArray();
        $callUsers = array_combine(
            array_column($callUsers, 'user_id'),
            array_values($callUsers)
        );

        $commentIds = array_column($list, 'comment_id');
        $comments = VideoComment::select(['id', 'video_id', 'content'])->whereIn('id', $commentIds)->get()->toArray();
        $comments = array_combine(
            array_column($comments, 'id'),
            array_values($comments)
        );

        $videoIds = array_column($comments, 'video_id');
        $videos = Video::select(['id', 'thumb', 'desc'])->whereIn('id', $videoIds)->get()->toArray();
        $videos = array_combine(
            array_column($videos, 'id'),
            array_values($videos)
        );

        foreach ($list as $key=>$item) {
            $item['user_info'] = $callUsers[$item['user_id']];

            $commentInfo = $comments[$item['comment_id']];

            $video = $videos[$commentInfo['video_id']];
            $video['thumb'] = full_url($video['thumb']);
            $item['video_info'] = $video;

            $item['comment_info'] = $commentInfo;

            $item['format_time'] = diff_time($item['created_time']);
            $list[$key] = $item;
        }

        return Page::wrap($totalCount, $page, $length, $list);
    }

    public static function add($commentId, $userIds)
    {
        if (count($userIds) == 0) {
            return;
        }

        $followers = UserFollowing::where('user_id', get_user_id())->whereIn('following_user_id', $userIds)->get()->toArray();
        $followerIds = array_column($followers, 'following_user_id');

        $userIds = array_intersect($followerIds, $userIds);

        $insertData = [];

        foreach ($userIds as $userId) {
            $insertData[] = [
                'user_id' => get_user_id(),
                'comment_id' => $commentId,
                'call_user_id' => $userId,
                'created_time' => date('Y-m-d H:i:s')
            ];
        }

        CallUser::insert($insertData);
    }
}